package com.runchinaup.sifitbledome.ble;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by liber on 2018/3/15.
 */

public class ScanHelper {

    private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    private Context context;
    private ScanListener scanListener;

    private static ScanHelper scanHelper;

    private ScanHelper(Context context) {
        this.context = context;
    }

    public static ScanHelper getScanHelper(Context context) {
        if (scanHelper == null) {
            synchronized (ScanHelper.class) {
                if (scanHelper == null) {
                    scanHelper = new ScanHelper(context);
                }
            }
        }
        return scanHelper;
    }

    //开始扫描
    public void startScan(ScanListener scanListener) {
        this.scanListener = scanListener;
        stopScan();
        bluetoothAdapter.startLeScan(leScanCallback);
        Log.e("debug_start_scan", "开始扫描");

        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                stopScan();
            }
        }, 8000);
    }

    //停止扫描
    public void stopScan() {
        bluetoothAdapter.stopLeScan(leScanCallback);
        Log.e("debug_stop_scan", "停止扫描");
    }

    //蓝牙扫描的回调
    final BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            if (!TextUtils.isEmpty(device.getName())) {
                scanListener.onScanCallback(device, rssi, scanRecord);
            }
        }
    };

    //回调扫描结果
    public interface ScanListener {
        void onScanCallback(BluetoothDevice device, int rssi, byte[] scanRecord);
    }

}
